import Vue from 'vue'
import Vuex from 'vuex'
import axios from '../utils/request'
Vue.use(Vuex)

const myPlugin = (store) => {
  store.subscribe((mutation, state) => {
    console.log('mutation:', mutation)
    localStorage.setItem('state', JSON.stringify(state))
  })
}

export default new Vuex.Store({
  state: {
    total: 0,
    list: JSON.parse(localStorage.getItem('state'))?.list || [],
    cartList: JSON.parse(localStorage.getItem('state'))?.cartList || [],
    token: JSON.parse(localStorage.getItem('state'))?.token || '',
    detailItem: {},
  },
  getters: {
    totalPrice(state) {
      return state.cartList.reduce((num, item) => {
        return num + item.count * item.price
      }, 0)
    },
  },
  mutations: {
    // set-token
    setToken(state, token) {
      state.token = token
    },
    setList(state, data) {
      state.list = data.list
      state.total = data.total
    },
    // 加入
    toCart(state, item) {
      const goods = state.cartList.find((v) => v.id === item.id)
      if (goods) {
        goods.count++
      } else {
        item.count = 1
        state.cartList.push(item)
      }
    },
    // +
    addItem(state, item) {
      item.count++
    },
    // -
    reduceItem(state, item) {
      if (item.count <= 1) {
        if (window.confirm('remove?')) {
          state.cartList.splice(
            state.cartList.findIndex((v) => v.id === item.id),
            1
          )
        }
        return
      }
      item.count--
    },
    // detail
    setDetailItem(state, item) {
      state.detailItem = item
    },
  },
  actions: {
    async getCartList({ commit }, params) {
      const res = await axios.get('/api/list', { params })
      commit('setList', res.data.data)
      return res.data
    },
    // login
    async loginFunc({ commit }, data) {
      const res = await axios.post('/api/login', data)
      commit('setToken', res.data.data.token)
      return res.data
    },
    async detailFunc({ commit }, { id }) {
      const res = await axios.get('/api/detail', { params: { id } })
      commit('setDetailItem', res.data.data[0])
      return res.data
    },
  },
  plugins: [myPlugin],
  modules: {},
})
